import { ref } from "vue";
import { useRouter } from "vue-router";

let routerId = 1;
const routerStack = ref([]);

export function useNavigation() {
  const router = useRouter();
  /**
   * Programmatically navigate to a new URL by pushing an entry in the history
   * stack.
   * @param  {import('vue-router').RouteLocationRaw} toRouter - Route location to navigate to
   * @returns {number}
   */
  function push(toRouter) {
    const id = routerId++;
    router.push(toRouter).then((v) => {
      // 跳转完成
      if (!v) {
        // 导航成功
        const afterRouter = router.currentRoute.value;
        routerStack.value.push({
          ...afterRouter,
          id,
        });
      }
    });
    return id;
  }

  /**
   * Programmatically navigate to a new URL by replacing the current entry in
   * the history stack.
   * @param  {import('vue-router').RouteLocationRaw} toRouter - Route location to navigate to
   * @returns {number}
   */
  function replace(toRouter, id) {
    router.replace(toRouter).then((v) => {
      if (v) {
        return;
      }
      const afterRouter = router.currentRoute.value;
      const index = routerStack.value.findIndex((item) =>
        id ? item.id === id : item.fullPath === afterRouter.fullPath
      );
      if (index === -1) {
        return;
      }
      routerStack.value.splice(index, 1, {
        ...afterRouter,
        id,
      });
    });
  }
  /**
   * Allows you to move forward or backward through the history. Calls
   * `history.go()`.
   *
   * @param delta - The position in the history to which you want to move,
   * relative to the current page
   */
  function go(delta) {
    router.go(delta);
  }

  /**
   * Go back in history if possible by calling `history.back()`. Equivalent to
   * `router.go(-1)`.
   */
  function back() {
    go(-1);
  }
  /**
   * Go forward in history if possible by calling `history.forward()`.
   * Equivalent to `router.go(1)`.
   */
  function forward() {
    go(1);
  }

  function removeNav(id) {
    routerStack.value = routerStack.value.findIndex((item) => item.id === id);
  }

  return { push, replace, go, back, forward, removeNav, routerStack };
}
